const { Schema } = require('./connect')

const ObjectId = Schema.Types.ObjectId

const ArticleSchema = new Schema({
  title: String,
  content: String,
  author: {
    type: ObjectId,
    ref: "users"
  }, // 关联 users 的表
  tips: String,
  commentNum: Number
}, {
  versionKey: false,
  timestamps: {
    createdAt: "created", // 创建时间 
    updatedAt: "updated"
  }
})

ArticleSchema.post("remove", doc => {
  const Comment = require("../Models/comment")
  const User = require("../Models/user")
  
  const {author, _id} = doc
  // 更新user 的 articleNum
  User
    .updateOne({_id: author}, {$inc: {articleNum: -1}})
    .exec()
  // 获取article 下的所有的 comment
  Comment
    .find({article: _id})
    .then(data => {
      data.forEach(comment => {
        comment.remove()
      })
    })
  
})

module.exports = ArticleSchema